-module(proxy_test).
-export([start/0]).

start() ->
    case gen_tcp:connect({127,0,0,1}, 1234, [binary]) of
        {ok, Socket} ->
            Request = "GET /index.html HTTP/1.1\r\nHost: 127.0.0.1\r\n\r\nGET /index.html HTTP/1.1\r\nHost: 127.0.0.1\r\n\r\n",
            gen_tcp:send(Socket, [list_to_binary(Request)]),
            inet:setopts(Socket, [{packet, http}, {active, once}]),
            recv(Socket);
        Error ->
            Error
    end.

recv(Socket) ->
    receive
        {http_response, Socket, Version, Status, Message} ->
            io:format("~p ~p ~p~n", [Version, Status, Message]),
            headers(Socket, 0);
        {tcp_closed, Socket} ->
            io:format("Connection cloesd by foreign host~n");
        Other ->
            Opt = inet:getopts(Socket, [packet, active]),
            io:format("opt for ~p is ~p~n", [Socket, Opt]),
            io:format("Other is: ~p~n", [Other])
    end.

headers(Socket, Len) ->
    case gen_tcp:recv(Socket, 0) of
        {ok, http_eoh} ->
            inet:setopts(Socket, [{packet, raw}]),
            get_body(Socket, Len);
        {ok, {http_header, _, 'Content-Length', _, Length}} ->
            io:format("Content-Length: ~p~n", [Length]),
            headers(Socket, Length);
        {ok, {http_header, _, Name, _, Value}} ->
            io:format("~s: ~s~n", [Name, Value]),
            headers(Socket, Len)
    end.

get_body(Socket, Len) ->
    Length = list_to_integer(Len),
    case gen_tcp:recv(Socket, Length) of
        {ok, Body} ->
            io:format("~n~s~n", [Body]),
            inet:setopts(Socket, [{packet, http}, {active, once}]),
            recv(Socket);
        Other ->
            Other
    end.
